package com.rj2002.ctrl;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rj2002.pojo.User;
import com.rj2002.service.UserService;
import com.rj2002.util.FileDownLoadUtils;

@Controller
@RequestMapping("/user")
public class UserCtrl {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/login")
	public String loginJsp() {
		return "login";
	}
	
	@RequestMapping("/reg")
	public String regJsp() {
		return "register";
	}
	
	@RequestMapping("/userregister")
	public String userregister(User user,Model model) {
		System.out.println(user);
		int i = userService.inserIntoUser(user);
		if(i != 1) {
			model.addAttribute("registerMsg", "注册失败了 憨憨");
			return "register";
		}else {
			return "login";
		}
	}
	
	@RequestMapping("/down")
	public void download(String path,HttpServletRequest request,HttpServletResponse response) throws IOException {
		FileDownLoadUtils.download(path, response);
	}
	
	@RequestMapping("/usercheckname")
	@ResponseBody
	public int usercheckname(String name,HttpServletRequest request) {
		return userService.usercheckname(name);
	}
	
	@RequestMapping("/userlogin")
	public String userlogin(User user,Model model,HttpServletRequest request,HttpServletResponse response) {
		HttpSession session = request.getSession();
		//查询数据库
		List<User> users = userService.userlogin(user);
		if(users.size() > 0) {
			user = users.get(0);
			session.setAttribute("account", user);
			//要跳转到哪里去
			System.out.println(user);
			if (user.getRole() == 0) {
				//买家
				return null;
			}else if(user.getRole() == 1){
				//商家
				return "saler/main";
			}else {
				//管理员的首页
				return "admin";
			}
		}else {
			model.addAttribute("registerMsg", "登录失败");
			return "login";
		}
	}
	
	@RequestMapping("/userloginout")
	public void userloginout(HttpServletRequest request,HttpServletResponse response) throws IOException {
		//清理session里的缓存
		HttpSession session = request.getSession();
		session.removeAttribute("account");
		response.sendRedirect("login"); 
	}
}
